package org.wsjy.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wsjy.exception.NullException;
import org.wsjy.mapper.THomeShowMapper;
import org.wsjy.model.THomeShow;
import org.wsjy.util.DateUtil;

/**
 * 首页展示服务
 * 
 * @Title:
 * @Company:万世极缘网络工作室
 * @Description:
 * @Author:wsjy
 * @Since:2016年1月16日
 * @Copyright:Copyright (c) 2016
 * @ModifyDate:
 * @Version:1.1.0
 */
@Service
public class HomeShowService {

    @Autowired
    private THomeShowMapper homeShowMapper;

    /**
     * 查询所有的展示信息，并做一定的封装
     * 
     * @return
     * @throws NullException
     * @Description:
     * @Authhor:wsjy
     */
    public Map<String, List<THomeShow>> findList() throws NullException {
        List<THomeShow> homeShowList = homeShowMapper.findAllList();
        // 将首页展示项进行封装
        Map<String, List<THomeShow>> homeShowMapList = new HashMap<String, List<THomeShow>>();
        List<THomeShow> homeShowRootList = homeShowMapList.get("root");
        // 非空判断
        if (homeShowList != null) {
            // 遍历展示项
            for (THomeShow homeShow : homeShowList) {
                if (homeShow.getBoRoot() != null && homeShow.getBoRoot()) {
                    if (homeShowRootList == null) {
                        homeShowRootList = new ArrayList<THomeShow>();
                        homeShowMapList.put("root", homeShowRootList);
                    }
                    // 放进根目录中
                    homeShowRootList.add(homeShow);
                } else {
                    // 为子展示项
                    String stParentId = homeShow.getStParentId();
                    // 将homeShow放进对应的Map中
                    List<THomeShow> childList = homeShowMapList.get(stParentId);
                    if (childList == null) {
                        childList = new ArrayList<THomeShow>();
                        homeShowMapList.put(stParentId, childList);
                    }
                    childList.add(homeShow);
                }
            }
        } else {
            throw new NullException(NullException.ERROR_CODE_NO_DATA, "未配置首页展示信息，请联系管理员！");
        }

        return homeShowMapList;
    }

    /**
     * 
     * @param homeShow
     * @Description:
     * @Authhor:wsjy
     */
    public void save(THomeShow homeShow) {
        homeShow.setStId(UUID.randomUUID().toString());
        homeShow.setDtCreateTime(DateUtil.getNow());
        homeShowMapper.insert(homeShow);
    }

    public void update(THomeShow homeShow) {
        homeShow.setDtUpdateTime(DateUtil.getNow());
        homeShowMapper.update(homeShow);
    }
}
